<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ghost ESP</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* CSS Variables for Colors and Fonts */
        :root {
            --background-color: #0a0a0f;
            --surface-color: #12121a;
            --primary-color: #ff6b00;
            --secondary-color: #3e1900;
            --accent-color: #9c27b0;
            --text-primary: #ffffff;
            --text-secondary: rgba(255, 255, 255, 0.7);
            --gradient-1: linear-gradient(135deg, #ff6b00, #9c27b0);
            --gradient-2: linear-gradient(45deg, #cc5500, #ff6b00);
            --card-bg: rgba(18, 18, 26, 0.8);
            --border-color: #ff6b00;
            --tooltip-bg: #000000;
            --tooltip-text: #ffffff;
            --input-bg: rgba(30, 30, 30, 0.6);
            --input-border: #ff6b00;
            --font-display: 'Inter', sans-serif;
            --font-mono: 'JetBrains Mono', monospace;
            --font-body: 'Inter', sans-serif;
        }

        /* Reset Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Global Styles */
        html, body {
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: var(--font-body);
            background-color: var(--background-color);
            color: var(--text-primary);
            line-height: 1.6;
            position: relative;
            overflow-x: hidden;
            min-height: 100vh;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        /* Enhanced Background Effect */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 20%, rgba(156, 39, 176, 0.15), transparent 40%),
                radial-gradient(circle at 80% 80%, rgba(255, 107, 0, 0.15), transparent 40%),
                radial-gradient(circle at 50% 50%, rgba(156, 39, 176, 0.1), transparent 60%),
                repeating-linear-gradient(45deg, rgba(156, 39, 176, 0.03) 0px, rgba(156, 39, 176, 0.03) 1px, transparent 1px, transparent 10px),
                repeating-linear-gradient(-45deg, rgba(255, 107, 0, 0.03) 0px, rgba(255, 107, 0, 0.03) 1px, transparent 1px, transparent 10px);
            z-index: -1;
            pointer-events: none;
        }

        /* Container Styles */
        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            position: relative;
            z-index: 1;
        }

        /* Typography */
        h1, h2, h3 {
            font-family: var(--font-display);
            color: var(--text-primary);
            text-align: center;
            margin: 2rem 0;
            font-weight: 600;
            letter-spacing: -0.02em;
        }

        h1 {
            font-size: 2.5rem;
            background: var(--gradient-1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-top: 3rem;
        }

        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            appearance: none;
            margin: 0;
        }

        /* Tabs Styling */
        .tab {
            display: flex;
            justify-content: space-around;
            border-radius: 12px;
            margin-bottom: 30px;
            padding: 4px;
        }

        .tab button {
            max-width: none;
            flex: 1;
            background: none;
            border: none;
            border-radius: 6px;
            outline: none;
            cursor: pointer;
            padding: 15px 0;
            margin: 0 2px;
            font-size: 18px;
            color: var(--primary-color);
            background-color: #311f13;
            transition: background-color 0.3s, color 0.3s;
        }

        .tab button:first-child {
            margin-left: 0;
        }

        .tab button:last-child {
            margin-right: 0;
        }

        .tab button:hover,
        .tab button.active {
            background-color: var(--accent-tone);
            color: #ffffff;
        }

        /* Tab Content */
        .tabcontent {
            display: none;
            animation: fadeEffect 0.5s;
        }

        .tabcontent.show {
            display: block;
        }

        @keyframes fadeEffect {
            from {opacity: 0;}
            to {opacity: 1;}
        }

        .breadcrumb {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            margin-bottom: 20px;
        }

        .breadcrumb-item {
            color: var(--primary-color-faded);
            cursor: pointer;
            margin-right: 8px;
            position: relative;
            padding: 4px 0;
            font-weight: bold;
            transition: color 0.3s;
        }

        .breadcrumb-item:hover {
            color: var(--primary-color);
        }

        .breadcrumb-item::after {
            content: '/';
            margin-left: 8px;
            color: #ffffff7f;
        }

        .breadcrumb-item:last-child::after {
            content: '';
        }

        .breadcrumb-item:last-child {
            cursor: default;
            color: #ffffff;
        }

        /* File Explorer Styling */
        .file-explorer {
            list-style-type: none;
            padding: 0;
        }

        .file-explorer li {
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 15px;
            position: relative;
            background-color: var(--tooltip-bg);
            border-left: 2px solid var(--border-color);
            border-right: 2px solid var(--border-color);
            border-top: 0.5px solid var(--accent-color);
            border-bottom: 0.5px solid var(--accent-color);
            border-radius: var(--li-br-top) var(--li-br-top) var(--li-br-bottom) var(--li-br-bottom);
            transition: background-color 0.3s;
            --li-br-top: 0;
            --li-br-bottom: 0;
        }

        .file-explorer li:hover:has(.file-name.folder) {
            background-color: var(--accent-color);
            cursor: pointer;
        }

        .file-explorer li:first-child {
            border-top: 2px solid var(--border-color);
            --li-br-top: 8px;
        }

        .file-explorer li:last-child {
            border-bottom: 2px solid var(--border-color);
            --li-br-bottom: 8px;
        }

        .file-explorer li:before {
            content: '';
            position: absolute;
            right: 15px;
            top: 54%;
            transform: translateY(-50%);
            pointer-events: none;
            color: var(--text-primary);
            font-size: 14px;
        }

        .file-explorer li:has(.file-name.folder):before {
            content: '\25B6';
        }

        .file-explorer li button {
            margin: 0;
        }

        .file-explorer .file-name {
            display: flex;
            align-items: center;
            cursor: default;
            color: var(--text-primary);
        }

        .file-explorer .file-name.folder {
            cursor: pointer;
            color: var(--text-primary);
        }

        .file-explorer .file-name.folder::before {
            content: '📁';
            margin-right: 10px;
        }

        .file-explorer .file-name.file::before {
            content: '📄';
            margin-right: 10px;
        }

        .file-explorer .file-actions {
            display: flex;
            gap: 15px;
        }

        /* Upload Section Styling */
        .upload-section {
            margin-top: 30px;
            padding: 20px;
            background-color: var(--secondary-color);
            border: 2px solid var(--border-color);
            border-radius: 8px;
        }

        .upload-section > :first-child {
            margin-top: 0;
        }

        .upload-section > :last-child {
            margin-bottom: 0;
        }

        .upload-section h3 {
            text-align: center;
            color: var(--primary-color);
            margin-bottom: 20px;
        }

        .upload-section input[type="file"] {
            padding: 10px;
            font-size: 16px;
            background-color: var(--input-bg);
            border: 2px solid var(--input-border);
            color: var(--text-primary);
            border-radius: 6px;
            transition: border-color 0.3s, background-color 0.3s;
        }

        .upload-section input[type="file"]:focus {
            border-color: var(--border-color);
            background-color: #000000;
            outline: none;
        }

        .upload-section button {
            width: 150px;
        }

        /* Settings Grid */
        .settings-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 28px;
        }

        .settings-section {
            flex: 1 1 calc(50% - 20px);
            background-color: var(--secondary-color);
            border: 2px solid var(--border-color);
            padding: 20px;
            border-radius: 30px;
            position: relative;
        }

        .settings-section > :first-child {
            margin-top: 0;
        }

        .settings-section > :last-child {
            margin-bottom: 0;
        }

        @media (max-width: 768px) {
            .settings-section {
                flex: 1 1 100%;
            }
        }

        label {
            display: block;
            margin-bottom: 4px;
            font-size: 16px;
        }

        .input-group {
            margin-bottom: 24px;
            text-align: left;
        }

        .input-group:has(input[type="file"]), .input-group:has(.toggle-switch), .input-group:has(.select-wrapper) {
            display: flex;
            justify-content: space-between;
        }

        input[type="number"],
        input[type="text"],
        input[type="color"],
        select,
        textarea {
            width: 100%;
            padding: 10px 15px;
            font-family: inherit;
            font-size: 16px;
            background-color: var(--gradient-2);
            border: 2px solid var(--gradient-2);
            color: var(--text-color);
            border-radius: 6px;
            margin-top: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s, background-color 0.3s;
        }

        input[type="number"]:focus,
        input[type="text"]:focus,
        input[type="color"]:focus,
        select:focus,
        textarea:focus {
            border-color: var(--primary-color);
            background-color: #1a0d00;
            outline: none;
        }

        /* Toggle Switch */
        .toggle-switch {
            position: relative;
            width: 60px;
            height: 30px;
            margin: 0;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            background-color: var(--accent-color);
            border-radius: 34px;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            transition: background-color 0.4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            width: 22px;
            background-color: var(--primary-color);
            border-radius: 50%;
            left: 4px;
            bottom: 4px;
            aspect-ratio: 1 / 1;
            transition: transform 0.4s, background-color 0.4s;
        }

        input:checked + .slider {
            background-color: var(--primary-color);
        }

        input:checked + .slider:before {
            background-color: var(--background-color);
            transform: translateX(28px);
        }

        /* Buttons */
        button {
            background: rgba(0, 0, 0, 0.5);
            color: var(--primary-color);
            border: 2px solid var(--primary-color);
            padding: 12px 25px;
            border-radius: 25px;
            cursor: pointer;
            font-family: var(--font-mono);
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            /* Center the buttons */
            display: block;
            margin: 20px auto;
            min-width: 150px;
            max-width: 220px;
            width: 100%;
        }

        button:hover {
            background: var(--primary-color);
            color: var(--background-color);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            transform: translateY(-1px);
        }

        button.small {
            padding: 8px 20px;
            font-size: 0.9em;
            border-width: 1px;
            display: inline-block;
            width: auto;
            min-width: auto;
            margin: 0;
        }

        /* Textarea */
        textarea {
            resize: vertical;
            min-height: 80px;
        }

        /* SD Card Explorer */
        #console,
        .console {
            background-color: var(--secondary-color);
            color: var(--primary-color);
            padding: 20px;
            height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', Courier, monospace;
            white-space: pre-wrap;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 2px solid var(--border-color);
        }

        /* Select Wrapper */
        .select-wrapper {
            position: relative;
            width: 100%;
            max-width: 300px;
            margin: 0;
        }

        .select-wrapper select {
            width: 100%;
            padding: 10px 15px;
            font-size: 16px;
            background-color: var(--input-bg);
            border: 2px solid var(--input-border);
            color: var(--text-color);
            border-radius: 6px;
            appearance: none;
            cursor: pointer;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: none;
            transition: border-color 0.3s, background-color 0.3s;
        }

        .select-wrapper select:focus {
            border-color: var(--primary-color);
            background-color: #1a0d00;
            outline: none;
        }

        .select-wrapper::after {
            content: '\25BC'; /* Down arrow */
            position: absolute;
            right: 15px;
            top: 54%;
            transform: translateY(-50%);
            pointer-events: none;
            color: var(--primary-color);
            font-size: 14px;
        }

        .file-wrapper {
            display: flex;
            align-items: center;
        }

        .file-wrapper button {
            margin: 0 0 0 20px;
        }

        .file-wrapper input[type="file"] {
            display: none;
        }

        .file-wrapper span {
            color: #ffffff7f;
            max-width: 200px;
        }

        /* Tooltip Styling */
        .tooltip {
            position: relative;
            display: inline-block;
            cursor: help;
            margin-left: 5px;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 220px;
            background-color: var(--tooltip-bg);
            color: var(--tooltip-text);
            text-align: center;
            border-radius: 6px;
            border: 2px solid var(--primary-color);
            filter: drop-shadow(0 0 13px rgb(0 0 0 / 0.3)) drop-shadow(0 0 5px rgb(0 0 0 / 0.8));
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%; /* Position above */
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip .tooltiptext::after {
            content: "";
            position: absolute;
            top: 100%; /* Bottom of tooltip */
            left: 50%;
            transform: translateX(-50%);
            border-width: 5px;
            border-style: solid;
            border-color: var(--primary-color) transparent transparent transparent;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* Disabled Section Styling */
        .disabled-section {
            opacity: 0.6;
            pointer-events: none;
            position: relative;
        }

        .disabled-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-color);
            font-size: 20px;
            pointer-events: none;
        }

        /* Dropzone Styling */
        .dropzone {
            border: 3px dashed var(--primary-color);
            padding: 30px;
            text-align: center;
            color: var(--primary-color);
            background-color: var(--secondary-color);
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s, border-color 0.3s;
        }

        .dropzone.dragover {
            background-color: var(--accent-color);
            border-color: #ffffff;
        }

        /* Help List Styling */
        .help-list {
            list-style-type: none;
            padding: 0;
        }

        .help-list li {
            background-color: var(--tooltip-bg);
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 16px 20px;
            margin-bottom: 15px;
            color: var(--text-primary);
        }

        .help-list code {
            background-color: rgba(0, 0, 0, 0.3);
            padding: 2px 4px;
            border-radius: 4px;
            color: var(--primary-color);
        }

        /* Responsive Enhancements */
        @media (max-width: 600px) {
            .tab button {
                font-size: 16px;
                padding: 12px 0;
            }

            button {
                padding: 12px 20px;
                font-size: 14px;
            }

            .select-wrapper::after {
                font-size: 14px;
            }
        }

        /* Settings Section Styles */
        .settings-section {
            background: rgba(10, 10, 15, 0.8);
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            backdrop-filter: blur(10px);
        }

        .settings-section h2 {
            color: var(--primary-color);
            font-size: 1.8rem;
            margin-bottom: 20px;
            text-align: left;
            background: none;
            -webkit-text-fill-color: var(--primary-color);
        }

        .settings-section label {
            color: var(--primary-color);
            font-weight: 500;
            margin-bottom: 8px;
            display: block;
        }

        .input-group {
            margin-bottom: 20px;
        }

        /* Input Styles */
        input[type="number"],
        input[type="text"],
        input[type="color"],
        select,
        textarea {
            border-radius: 12px;
            border: 2px solid var(--border-color);
            padding: 12px 15px;
            transition: all 0.3s ease;
            background: rgba(0, 0, 0, 0.3);
        }

        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(255, 107, 0, 0.1);
            transform: translateY(-1px);
        }

        /* Tooltip Styles */
        .tooltip .tooltiptext {
            background-color: rgba(0, 0, 0, 0.9);
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
        }

        /* Button Styles */
        button {
            background: rgba(0, 0, 0, 0.5);
            color: var(--primary-color);
            border: 2px solid var(--primary-color);
            padding: 12px 25px;
            border-radius: 25px;
            cursor: pointer;
            font-family: var(--font-mono);
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            /* Center the buttons */
            display: block;
            margin: 20px auto;
            min-width: 150px;
            max-width: 220px;
            width: 100%;
        }

        button:hover {
            background: var(--primary-color);
            color: var(--background-color);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            transform: translateY(-1px);
        }

        /* Small button variant - override centering for inline buttons */
        button.small {
            padding: 8px 20px;
            font-size: 0.9em;
            border-width: 1px;
            display: inline-block;
            width: auto;
            min-width: auto;
            margin: 0;
        }

        /* For button containers that need inline buttons */
        .file-wrapper button,
        .file-actions button {
            display: inline-block;
            width: auto;
            min-width: auto;
            margin: 0 5px;
        }

        /* Tab buttons should be inline and equal width */
        .tab button {
            display: inline-block;
            width: auto;
            min-width: auto;
            margin: 0 4px;
        }

        /* Terminal Styling */
        .terminal-container {
            background: rgba(10, 10, 15, 0.95);
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            height: calc(100vh - 200px);
            min-height: 400px;
            display: flex;
            flex-direction: column;
        }

        .terminal-output {
            flex: 1;
            background-color: rgba(0, 0, 0, 0.7);
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
            font-family: var(--font-mono);
            color: var(--text-primary);
            white-space: pre-wrap;
            word-wrap: break-word;
            font-size: 14px;
            line-height: 1.4;
            overflow-y: auto;
            overflow-x: hidden;
            scrollbar-width: thin;
            scrollbar-color: var(--primary-color) var(--background-color);
        }

        .terminal-output::-webkit-scrollbar {
            width: 8px;
        }

        .terminal-output::-webkit-scrollbar-track {
            background: var(--background-color);
            border-radius: 4px;
        }

        .terminal-output::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 4px;
        }

        .terminal-input-container {
            display: flex;
            gap: 10px;
            margin-top: auto;
            padding-top: 15px;
            border-top: 1px solid var(--border-color);
        }

        .terminal-input-container input {
            flex: 1;
            background-color: rgba(0, 0, 0, 0.5);
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 15px;
            color: var(--text-primary);
            font-family: var(--font-mono);
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .terminal-input-container input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(255, 107, 0, 0.2);
            background-color: rgba(0, 0, 0, 0.7);
        }

        .terminal-input-container button {
            min-width: 100px;
            margin: 0;
            padding: 12px 20px;
            font-size: 14px;
            background: rgba(255, 107, 0, 0.1);
            transition: all 0.3s ease;
        }

        .terminal-input-container button:hover {
            background: var(--primary-color);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(255, 107, 0, 0.3);
        }

        @media (max-width: 768px) {
            .terminal-container {
                height: calc(100vh - 150px);
                min-height: 300px;
            }

            .terminal-input-container {
                flex-direction: column;
                gap: 8px;
            }

            .terminal-input-container button {
                width: 100%;
            }
        }

        @media (max-width: 480px) {
            .terminal-container {
                padding: 10px;
                height: calc(100vh - 120px);
            }

            .terminal-output {
                font-size: 12px;
                padding: 10px;
            }

            .terminal-input-container input,
            .terminal-input-container button {
                font-size: 12px;
                padding: 10px 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Ghost ESP vA1.4.7</h1>
        <!-- Tab Navigation -->
        <div class="tab">
            <button class="tablinks active" onclick="openTab(event, 'Settings')" id="defaultTab">Settings</button>
            <button class="tablinks" onclick="openTab(event, 'Help')">Help</button>
            <button class="tablinks" onclick="openTab(event, 'SDCard')">SD Card</button>
            <button class="tablinks" onclick="openTab(event, 'Terminal')">Terminal</button>
        </div>
        <!-- Settings Tab Content -->
        <div id="Settings" class="tabcontent show">
            <div class="settings-grid">
                <!-- WiFi/BLE Section -->
                <div class="settings-section" id="miscellaneous_section">
                    <h2>Miscellaneous Settings</h2>

                    <div class="input-group">
                        <label for="gps_rx_pin">GPS RX Pin
                            <span class="tooltip">?
                                <span class="tooltiptext">Provide the GPS RX Pin For the Firmware. Only for those who have a working GPS Installed</span>
                            </span>
                        </label>
                        <input type="number" id="gps_rx_pin" min="0" max="50" step="1" placeholder="0 - 50" required>
                    </div>

                    <div class="input-group">
                        <label for="flappy_name_text">Name 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the Name you want to have on the Flappy Ghost leaderboards.</span>
                            </span>
                        </label>
                        <textarea id="flappy_name_text" placeholder="Enter Name"></textarea>
                    </div>

                    <div class="input-group">
                        <label for="broadcast_speed">Broadcast Speed (ms) 
                            <span class="tooltip">?
                                <span class="tooltiptext">Set the speed at which broadcasts are sent, in milliseconds (5 - 1000 ms).</span>
                            </span>
                        </label>
                        <input type="number" id="broadcast_speed" min="5" max="1000" step="1" placeholder="5 - 1000 ms" required>
                    </div>
                    
                    <div class="input-group">
                        <label for="accent_color_picker">Accent Color 
                            <span class="tooltip">?
                                <span class="tooltiptext">Pick a custom accent color for the firmware. Use the color picker to select your preferred color.</span>
                            </span>
                        </label>
                        <input type="color" id="accent_color_picker" value="#ffffff">
                        <span id="accent_color_hex" style="margin-left: 10px;">#ffffff</span>
                    </div>

                </div>
                <!-- Connect to WiFi Section (Disabled) -->
                <div class="settings-section" id="connect-wifi-section">
                    <h2>WiFi Status</h2>
                    <div class="input-group">
                        <label for="station_ip">ESP32 Station IP:</label>
                        <input type="text" id="station_ip" placeholder="Not connected" readonly>
                    </div>
                    <h2>Connect to WiFi Network</h2>
                    <div class="input-group">
                        <label for="wifi_ssid">WiFi SSID 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the SSID of the WiFi network you want to connect to.</span>
                            </span>
                        </label>
                        <input type="text" id="wifi_ssid" placeholder="Enter WiFi SSID">
                    </div>
                    <div class="input-group">
                        <label for="wifi_password">WiFi Password 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the password of the WiFi network you want to connect to.</span>
                            </span>
                        </label>
                        <input type="text" id="wifi_password" placeholder="Enter WiFi Password">
                    </div>
                    <button onclick="connectToWiFi()">Connect</button>
                </div>
                <!-- Evil Portal Section -->
                <div class="settings-section" id="evil-portal-section">
                    <h2>Evil Portal Settings</h2>
                    <div class="input-group">
                        <label for="portal_offline_mode">Offline Mode 
                            <span class="tooltip">?
                                <span class="tooltiptext">Toggle offline mode for the Evil Portal.</span>
                            </span>
                        </label>
                        <label class="toggle-switch">
                            <input type="checkbox" id="portal_offline_mode">
                            <span class="slider"></span>
                        </label>
                    </div>
                    <div class="input-group">
                        <label for="portal_url">Website URL or File Path 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the URL or file path for the Evil Portal.</span>
                            </span>
                        </label>
                        <input type="text" id="portal_url" placeholder="Enter URL">
                    </div>
                    <div class="input-group">
                        <label for="portal_ssid">WiFi SSID 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the SSID for the WiFi network used by the Evil Portal.</span>
                            </span>
                        </label>
                        <input type="text" id="portal_ssid" placeholder="Enter WiFi SSID">
                    </div>
                    <div class="input-group">
                        <label for="portal_password">WiFi Password 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the password for the WiFi network used by the Evil Portal.</span>
                            </span>
                        </label>
                        <input type="text" id="portal_password" placeholder="Enter WiFi Password">
                    </div>
                    <div class="input-group">
                        <label for="portal_ap_ssid">Evil Portal AP SSID 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the SSID for the Access Point of the Evil Portal.</span>
                            </span>
                        </label>
                        <input type="text" id="portal_ap_ssid" placeholder="Enter Evil Portal AP SSID">
                    </div>
                    <div class="input-group">
                        <label for="portal_domain">Portal Domain 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the domain name for the Evil Portal.</span>
                            </span>
                        </label>
                        <input type="text" id="portal_domain" placeholder="Enter Domain">
                    </div>
                    <button onclick="startevilportal()">Start Evil Portal</button>
                </div>
                <!-- Power Printer Section -->
                <div class="settings-section" id="power-printer-section">
                    <h2>Power Printer Settings</h2>
                    <div class="input-group">
                        <label for="printer_ip">Printer IP 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the IP address of the printer.</span>
                            </span>
                        </label>
                        <input type="text" id="printer_ip" placeholder="Enter Printer IP">
                    </div>
                    <div class="input-group">
                        <label for="printer_text">Printer Text 
                            <span class="tooltip">?
                                <span class="tooltiptext">Enter the text to print on the printer.</span>
                            </span>
                        </label>
                        <textarea id="printer_text" placeholder="Enter Text to Print"></textarea>
                    </div>
                    <div class="input-group">
                        <label for="printer_font_size">Printer Font Size 
                            <span class="tooltip">?
                                <span class="tooltiptext">Set the font size for the printed text (10 - 72).</span>
                            </span>
                        </label>
                        <input type="number" id="printer_font_size" min="10" max="72" step="1" placeholder="10 - 72" required>
                    </div>
                    <div class="input-group">
                        <label for="printer_alignment">Printer Alignment 
                            <span class="tooltip">?
                                <span class="tooltiptext">Select the alignment for the printed text.</span>
                            </span>
                        </label>
                        <div class="select-wrapper">
                            <select id="printer_alignment">
                                <option value="0">Center Middle</option>
                                <option value="1">Top Left</option>
                                <option value="2">Top Right</option>
                                <option value="3">Bottom Right</option>
                                <option value="4">Bottom Left</option>
                            </select>
                        </div>
                    </div>
                    <button onclick="sendtoprinter()">Send to Printer</button>
                </div>
                <!-- RGB Section -->
                <div class="settings-section" id="rgb-section">
                    <h2>RGB Settings</h2>
                    <div class="input-group">
                        <label for="rainbow_mode">Rainbow Mode 
                            <span class="tooltip">?
                                <span class="tooltiptext">Toggle the rainbow color mode for the RGB LEDs.</span>
                            </span>
                        </label>
                        <label class="toggle-switch">
                            <input type="checkbox" id="rainbow_mode">
                            <span class="slider"></span>
                        </label>
                    </div>
                    <div class="input-group">
                        <label for="rgb_speed">RGB Speed 
                            <span class="tooltip">?
                                <span class="tooltiptext">Set the speed of the RGB color change (15 - 50).</span>
                            </span>
                        </label>
                        <input type="number" id="rgb_speed" min="15" max="50" step="1" placeholder="15 - 50" required>
                    </div>
                    <div class="input-group">
                        <label for="rgb_red_pin">Red Pin 
                            <span class="tooltip">?
                                <span class="tooltiptext">GPIO for red LED (0-34)</span>
                            </span>
                        </label>
                        <input type="number" id="rgb_red_pin" min="0" max="34" placeholder="Red GPIO">
                    </div>
                    <div class="input-group">
                        <label for="rgb_green_pin">Green Pin 
                            <span class="tooltip">?
                                <span class="tooltiptext">GPIO for green LED (0-34)</span>
                            </span>
                        </label>
                        <input type="number" id="rgb_green_pin" min="0" max="34" placeholder="Green GPIO">
                    </div>
                    <div class="input-group">
                        <label for="rgb_blue_pin">Blue Pin 
                            <span class="tooltip">?
                                <span class="tooltiptext">GPIO for blue LED (0-34)</span>
                            </span>
                        </label>
                        <input type="number" id="rgb_blue_pin" min="0" max="34" placeholder="Blue GPIO">
                    </div>
                </div>
                <!-- Flappy Ghost Section -->
                <div class="settings-section" id="flappy_ghost_section">
                    <h2>Watch / RTC Settings</h2>
                    <div class="input-group">
                        <label for="timezone_select">Timezone 
                            <span class="tooltip">?
                                <span class="tooltiptext">Select your timezone. This will be used to adjust the device clock.</span>
                            </span>
                        </label>
                        <select id="timezone_select">
                            <option value="UTC0">UTC</option>
                            
                            <!-- United States Timezones -->
                            <option value="HST10">Hawaii-Aleutian Standard Time (HST)</option>
                            <option value="AKST9AKDT,M3.2.0,M11.1.0">Alaska Time (AKST/AKDT)</option>
                            <option value="PST8PDT,M3.2.0,M11.1.0">Pacific Time (PST/PDT)</option>
                            <option value="MST7MDT,M3.2.0,M11.1.0">Mountain Time (MST/MDT)</option>
                            <option value="CST6CDT,M3.2.0,M11.1.0">Central Time (CST/CDT)</option>
                            <option value="EST5EDT,M3.2.0,M11.1.0">Eastern Time (EST/EDT)</option>
                            <option value="AST4">Atlantic Standard Time (AST)</option>
                            
                            <!-- Australian Timezones -->
                            <option value="AWST-8">Australian Western Time (AWST)</option>
                            <option value="ACST-9:30">Australian Central Standard Time (ACST)</option>
                            <option value="ACDT-10:30,M10.1.0,M4.1.0/3">Australian Central Daylight Time (ACST/ACDT)</option>
                            <option value="AEST-10">Australian Eastern Standard Time (AEST)</option>
                            <option value="AEDT-11,M10.1.0,M4.1.0/3">Australian Eastern Daylight Time (AEST/AEDT)</option>
                            <option value="LHST-10:30">Lord Howe Standard Time (LHST)</option>
                            
                            <!-- Additional European Timezones -->
                            <option value="WET0WEST,M3.5.0/1,M10.5.0">Western European Time (WET/WEST)</option>
                            <option value="EET-2EEST,M3.5.0/3,M10.5.0/4">Eastern European Time (EET/EEST)</option>
                            
                            <!-- Additional Asian Timezones -->
                            <option value="PKT-5">Pakistan Standard Time (PKT)</option>
                            <option value="KST-9">Korea Standard Time (KST)</option>
                            <option value="PHT-8">Philippine Time (PHT)</option>
                            <option value="ICT-7">Indochina Time (ICT)</option>
                            
                            <!-- Additional Pacific Timezones -->
                            <option value="NZST-12NZDT,M9.5.0,M4.1.0/3">New Zealand Time (NZST/NZDT)</option>
                            <option value="FJT-12">Fiji Time (FJT)</option>
                            
                            <!-- Existing Other Common Timezones -->
                            <option value="IST-5:30">India Standard Time (IST)</option>
                            <option value="GMT0BST,M3.5.0/1,M10.5.0/2">British Summer Time (GMT/BST)</option>
                            <option value="CET-1CEST,M3.5.0,M10.5.0/3">Central European Time (CET/CEST)</option>
                            <option value="JST-9">Japan Standard Time (JST)</option>
                            <option value="CST-8">China Standard Time (CST)</option>
                        </select>
                    </div>
                    
                    <div class="input-group">
                        <label for="display_timeout">LilyGo T-Watch Display Timeout (ms)
                            <span class="tooltip">?
                                <span class="tooltiptext">Set how long before the display turns off when inactive (1000-60000 ms)</span>
                            </span>
                        </label>
                        <input type="number" id="display_timeout" min="1000" max="60000" step="1000" placeholder="1000 - 60000 ms" required>
                    </div>
                </div>
            </div>
            <button onclick="saveSettings()">Save Settings</button>
        </div>
        <!-- Help Tab Content -->
        <div id="Help" class="tabcontent">
            <div class="settings-grid">
                <div class="settings-section">
                    <h2>ESP32 Commands</h2>
                    <ul class="help-list">
                        <li>
                            <strong>help</strong>: Display this help message.<br>
                            <strong>Usage:</strong> <code>help</code>
                        </li>
                        <li>
                            <strong>scanap</strong>: Start a Wi-Fi access point (AP) scan.<br>
                            <strong>Usage:</strong> <code>scanap</code>
                        </li>
                        <li>
                            <strong>scansta</strong>: Start scanning for Wi-Fi stations.<br>
                            <strong>Usage:</strong> <code>scansta</code>
                        </li>
                        <li>
                            <strong>stopscan</strong>: Stop any ongoing Wi-Fi scan.<br>
                            <strong>Usage:</strong> <code>stopscan</code>
                        </li>
                        <li>
                            <strong>attack</strong>: Launch an attack (e.g., deauthentication attack).<br>
                            <strong>Usage:</strong> <code>attack -d</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-d</code>: Start deauth attack
                        </li>
                        <li>
                            <strong>list</strong>: List Wi-Fi scan results or connected stations.<br>
                            <strong>Usage:</strong> <code>list -a | list -s</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-a</code>: Show access points from Wi-Fi scan<br>
                            <code>-s</code>: List connected stations
                        </li>
                        <li>
                            <strong>beaconspam</strong>: Start beacon spam with different modes.<br>
                            <strong>Usage:</strong> <code>beaconspam [OPTION]</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-r</code>: Start random beacon spam<br>
                            <code>-rr</code>: Start Rickroll beacon spam<br>
                            <code>-l</code>: Start AP List beacon spam<br>
                            <code>[SSID]</code>: Use specified SSID for beacon spam
                        </li>
                        <li>
                            <strong>stopspam</strong>: Stop ongoing beacon spam.<br>
                            <strong>Usage:</strong> <code>stopspam</code>
                        </li>
                        <li>
                            <strong>stopdeauth</strong>: Stop ongoing deauthentication attack.<br>
                            <strong>Usage:</strong> <code>stopdeauth</code>
                        </li>
                        <li>
                            <strong>select</strong>: Select an access point by index from scan results.<br>
                            <strong>Usage:</strong> <code>select -a &lt;number&gt;</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-a</code>: AP selection index (must be a valid number)
                        </li>
                        <li>
                            <strong>startportal</strong>: Start a portal with specified parameters.<br>
                            <strong>Usage:</strong> <code>startportal &lt;URL&gt; &lt;SSID&gt; &lt;Password&gt; &lt;AP_ssid&gt; &lt;Domain&gt;</code><br>
                            <strong>Arguments:</strong><br>
                            <code>&lt;URL&gt;</code>: URL for the portal<br>
                            <code>&lt;SSID&gt;</code>: Wi-Fi SSID for the portal<br>
                            <code>&lt;Password&gt;</code>: Wi-Fi password for the portal<br>
                            <code>&lt;AP_ssid&gt;</code>: SSID for the access point<br>
                            <code>&lt;Domain&gt;</code>: Custom domain to spoof in address bar<br>
                            <em>OR</em><br>
                            <strong>Offline Usage:</strong> <code>startportal &lt;FilePath&gt; &lt;AP_ssid&gt; &lt;Domain&gt;</code>
                        </li>
                        <li>
                            <strong>stopportal</strong>: Stop the Evil Portal.<br>
                            <strong>Usage:</strong> <code>stopportal</code>
                        </li>
                        <li>
                            <strong>blescan</strong>: Handle BLE scanning with various modes.<br>
                            <strong>Usage:</strong> <code>blescan [OPTION]</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-f</code>: Start 'Find the Flippers' mode<br>
                            <code>-ds</code>: Start BLE spam detector<br>
                            <code>-a</code>: Start AirTag scanner<br>
                            <code>-r</code>: Scan for raw BLE packets<br>
                            <code>-s</code>: Stop BLE scanning
                        </li>
                        <li>
                            <strong>capture</strong>: Start a Wi-Fi capture (requires SD card or Flipper).<br>
                            <strong>Usage:</strong> <code>capture [OPTION]</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-probe</code>: Start capturing probe packets<br>
                            <code>-beacon</code>: Start capturing beacon packets<br>
                            <code>-deauth</code>: Start capturing deauth packets<br>
                            <code>-raw</code>: Start capturing raw packets<br>
                            <code>-wps</code>: Start capturing WPS packets and their auth type<br>
                            <code>-pwn</code>: Start capturing Pwnagotchi packets<br>
                            <code>-stop</code>: Stop the active capture
                        </li>
                        <li>
                            <strong>connect</strong>: Connect to a specific Wi-Fi network.<br>
                            <strong>Usage:</strong> <code>connect &lt;SSID&gt; &lt;Password&gt;</code>
                        </li>
                        <li>
                            <strong>dialconnect</strong>: Cast a random YouTube video on all smart TVs on LAN.<br>
                            <strong>Usage:</strong> <code>dialconnect</code>
                        </li>
                        <li>
                            <strong>powerprinter</strong>: Print custom text to a printer on LAN.<br>
                            <strong>Usage:</strong> <code>powerprinter &lt;Printer IP&gt; &lt;Text&gt; &lt;FontSize&gt; &lt;Alignment&gt;</code><br>
                            <strong>Alignment options:</strong> CM = Center Middle, TL = Top Left, TR = Top Right, BR = Bottom Right, BL = Bottom Left
                        </li>
                        <li>
                            <strong>blewardriving</strong>: Start/Stop BLE wardriving with GPS logging.<br>
                            <strong>Usage:</strong> <code>blewardriving [-s]</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-s</code>: Stop BLE wardriving
                        </li>
                        <li>
                            <strong>scanports</strong>: Scan ports on local subnet or specific IP.<br>
                            <strong>Usage:</strong> <code>scanports local [-C/-A/start_port-end_port]</code><br>
                            <code>scanports [IP] [-C/-A/start_port-end_port]</code><br>
                            <strong>Arguments:</strong><br>
                            <code>-C</code>: Scan common ports only<br>
                            <code>-A</code>: Scan all ports (1-65535)<br>
                            <code>start_port-end_port</code>: Custom port range (e.g. 80-443)
                        </li>
                        <li>
                            <strong>setrgbpins</strong>: Change RGB LED pins configuration.<br>
                            <strong>Usage:</strong> <code>setrgbpins &lt;red&gt; &lt;green&gt; &lt;blue&gt;</code><br>
                            <strong>Note:</strong> Use same value for all pins for single-pin LED strips
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- SD Card Tab Content -->
        <div id="SDCard" class="tabcontent">
            <div class="settings-grid">
                <!-- SD Card Explorer Section -->
                <div class="settings-section">
                    <h2>SD Card File Explorer</h2>
                    
                    <!-- Breadcrumb Navigation -->
                    <nav class="breadcrumb" id="breadcrumb">
                        <span class="breadcrumb-item" onclick="navigateToBreadcrumb(0)">Root</span>
                    </nav>
                    
                    <!-- SD Card Status -->
                    <div id="sdcard-status">
                        Loading SD card data...
                    </div>
                    
                    <!-- SD Card Structure -->
                    <div id="sdcard-structure">
                        <!-- SD Card Structure will be rendered here -->
                    </div>
                </div>

                <!-- Upload Section -->
                <div class="settings-section">
                    <h2>Upload File</h2>
                    <div class="input-group">
                        <label for="sdcard-upload">Choose File 
                            <span class="tooltip">?
                                <span class="tooltiptext">Select a file to upload to the current folder on the SD Card.</span>
                            </span>
                        </label>
                        <div class="file-wrapper">
                            <span id="upload-file-name">No files selected</span>
                            <button class="small" onclick="document.getElementById('sdcard-upload').click()">Upload</button>
                            <input type="file" id="sdcard-upload" accept="*/*" onchange="document.getElementById('upload-file-name').innerText = this.files[0].name">
                        </div>
                    </div>
                    <button onclick="uploadFile()">Upload</button>
                </div>
            </div>
        </div>
        
        <!-- Terminal Tab Content -->
        <div id="Terminal" class="tabcontent">
            <div class="settings-section terminal-container">
                <h2>Device Terminal</h2>
                <div id="terminalOutput" class="terminal-output"></div>
                <div class="terminal-input-container">
                    <input type="text" id="terminalInput" placeholder="Enter command...">
                    <button onclick="sendTerminalCommand()">Send</button>
                </div>
            </div>
        </div>
    </div>
    <!-- JavaScript for Interactivity -->
    <script>

        let sdCardData = [];          // Stores the entire SD Card structure
        let navigationStack = [];     // Keeps track of the navigation path
        let logOffset = 0;
        const termOutput = document.getElementById('terminalOutput');

        async function uploadFile() {
            const fileInput = document.getElementById('sdcard-upload');
            const file = fileInput.files[0];

            if (!file) {
                alert('Please select a file to upload.');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            // Determine the upload path based on the navigation stack
            const currentFolder = getCurrentFolder();
            let uploadPath = '/mnt';
            if (navigationStack.length > 1) {
                const pathParts = navigationStack.slice(1).map(folder => folder.name);
                uploadPath = '/mnt/' + pathParts.join('/');
            }

            try {
                // Show uploading status
                const statusElement = document.getElementById('sdcard-status');
                statusElement.textContent = 'Uploading file...';

                // Use the uploadPath as a query parameter in the URL
                const response = await fetch(`/api/sdcard/upload?path=${encodeURIComponent(uploadPath)}`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    alert('File uploaded successfully!');
                    fetchSDCardData();
                    statusElement.textContent = 'File uploaded successfully.';
                    fileInput.value = '';
                } else {
                    throw new Error(result.message || 'Failed to upload the file.');
                }
            } catch (error) {
                console.error('Error uploading file:', error);
                alert(`Error uploading file: ${error.message}`);
                const statusElement = document.getElementById('sdcard-status');
                statusElement.textContent = `Error: ${error.message}`;
            }
        }

        document.getElementById('accent_color_picker').addEventListener('input', function (event) {
            const hexColor = event.target.value;
            document.getElementById('accent_color_hex').textContent = hexColor;
        });


        async function fetchSDCardData() {
            const statusElement = document.getElementById("sdcard-status");
            try {
                const response = await fetch("/api/sdcard");
                const data = await response.json();
                
                if (response.ok) {
                    sdCardData = data; // Store the entire structure
                    navigationStack = [ { name: "Root", type: "folder", children: sdCardData } ]; // Initialize stack with root
                    renderCurrentFolder();
                    statusElement.textContent = "SD card data loaded successfully.";
                } else {
                    throw new Error(data.message || "Failed to fetch SD card data.");
                }
            } catch (error) {
                statusElement.textContent = error.message || "Failed to load SD card data.";
                console.error("Error fetching SD Card data:", error);
            }
        }



        function getCurrentFolder() {
            return navigationStack[navigationStack.length - 1];
        }

        function renderCurrentFolder() {
            const currentFolder = getCurrentFolder();
            const structureElement = document.getElementById("sdcard-structure");
            structureElement.innerHTML = ""; // Clear existing contents

            if (!currentFolder.children || currentFolder.children.length === 0) {
                structureElement.textContent = "This folder is empty.";
                return;
            }

            const ul = document.createElement("ul");
            ul.classList.add("file-explorer");

            currentFolder.children.forEach(item => {
                const li = document.createElement("li");

                const fileName = document.createElement("span");
                fileName.classList.add("file-name");
                fileName.textContent = item.name;

                if (item.type === "folder") {
                    fileName.classList.add("folder");
                    fileName.onclick = () => navigateIntoFolder(item);
                } else {
                    fileName.classList.add("file");
                }

                li.appendChild(fileName);

                if (item.type === "file") {
                    const actionContainer = document.createElement("div");
                    actionContainer.classList.add("file-actions");

                    const downloadBtn = document.createElement("button");
                    downloadBtn.textContent = "Download";
                    downloadBtn.classList.add("small");
                    downloadBtn.classList.add("download-button");
                    downloadBtn.onclick = () => downloadFile(item.path);
                    actionContainer.appendChild(downloadBtn);

                    const deleteBtn = document.createElement("button");
                    deleteBtn.textContent = "Delete";
                    deleteBtn.classList.add("small");
                    deleteBtn.classList.add("delete-button");
                    deleteBtn.onclick = () => deleteFile(item.name, item.path);
                    actionContainer.appendChild(deleteBtn);

                    li.appendChild(actionContainer);
                }

                ul.appendChild(li);
            });

            structureElement.appendChild(ul);
            updateBreadcrumb();
        }


        function updateBreadcrumb() {
            const breadcrumb = document.getElementById("breadcrumb");
            breadcrumb.innerHTML = ""; // Clear existing breadcrumbs

            navigationStack.forEach((folder, index) => {
                const crumb = document.createElement("span");
                crumb.classList.add("breadcrumb-item");
                crumb.textContent = folder.name;

                if (index < navigationStack.length - 1) {
                    crumb.onclick = () => navigateToBreadcrumb(index);
                } else {
                    // Current folder - not clickable
                    crumb.style.cursor = 'default';
                    crumb.style.color = '#ffffff';
                }

                breadcrumb.appendChild(crumb);
            });
        }

        function navigateIntoFolder(folder) {
            navigationStack.push(folder);
            renderCurrentFolder();
        }

        function navigateToBreadcrumb(index) {
            // Remove folders from the stack after the selected breadcrumb
            navigationStack = navigationStack.slice(0, index + 1);
            renderCurrentFolder();
        }

        function basename(path) {
            return path.split('/').reverse()[0];
        }

        async function downloadFile(filePath) {
            const response = await fetch("/api/sdcard/download", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ path: filePath })
            });

            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = basename(filePath); // Use the file name from the path
                a.click();
                window.URL.revokeObjectURL(url);
            } else {
                const errorData = await response.json();
                alert(errorData.message || "Failed to download the file.");
            }
        }

        async function deleteFile(fileName, filePath) {
            const confirmDelete = confirm("Are you sure you want to delete " + fileName + "?");
            if (!confirmDelete) return;

            const response = await fetch("/api/sdcard?path=" + encodeURI(filePath), {
                method: "DELETE",
                headers: { "Content-Type": "application/json" }
            });

            if (!response.ok) {
                const errorData = await response.json();
                alert(errorData.message || "Failed to delete the file.");
            }
            else
                fetchSDCardData();
        }

        // Function to handle tab switching
        function openTab(evt, tabName) {
            const tabcontent = document.getElementsByClassName("tabcontent");
            for (let i = 0; i < tabcontent.length; i++) {
                tabcontent[i].classList.remove("show");
            }
            const tablinks = document.getElementsByClassName("tablinks");
            for (let i = 0; i < tablinks.length; i++) {
                tablinks[i].classList.remove("active");
            }
            document.getElementById(tabName).classList.add("show");
            evt.currentTarget.classList.add("active");

            if (tabName === "SDCard") {
                fetchSDCardData();
            }
        }

        // Set the default tab to open on page load
        document.getElementById("defaultTab").click();

        // Function to load current settings from the ESP32
        function loadSettings() {
            fetch('/api/settings')
                .then(response => response.json())
                .then(data => {
                    // WiFi/BLE Settings
                    document.getElementById('broadcast_speed').value = data.broadcast_speed;

                    // RGB Settings
                    document.getElementById('rainbow_mode').checked = data.rainbow_mode;
                    document.getElementById('rgb_speed').value = data.rgb_speed;

                    // Evil Portal Settings
                    document.getElementById('portal_url').value = data.portal_url;
                    document.getElementById('portal_ssid').value = data.portal_ssid;
                    document.getElementById('portal_password').value = data.portal_password;
                    document.getElementById('portal_ap_ssid').value = data.portal_ap_ssid;
                    document.getElementById('portal_domain').value = data.portal_domain;
                    document.getElementById('portal_offline_mode').checked = data.portal_offline_mode;

                    // Power Printer Settings
                    document.getElementById('printer_ip').value = data.printer_ip;
                    document.getElementById('printer_text').value = data.printer_text;
                    document.getElementById('printer_font_size').value = data.printer_font_size;
                    document.getElementById('printer_alignment').value = data.printer_alignment;


                    // Flappy Ghost Settings
                    document.getElementById('flappy_name_text').value = data.flappy_ghost_name || '';

                    document.getElementById('accent_color_hex').textContent = data.hex_accent_color;
                    document.getElementById('timezone_select').value = data.timezone_str;

                    if (data.station_ip) {
                        document.getElementById('station_ip').value = data.station_ip;
                    } else {
                        document.getElementById('station_ip').value = 'Not connected';
                    }

                    // Display timeout setting
                    document.getElementById('display_timeout').value = data.display_timeout || DEFAULT_DISPLAY_TIMEOUT_MS;
                })
                .catch(error => console.error('Error fetching settings:', error));
        }

        // Function to save settings to the ESP32
        function saveSettings() {
            const settings = {
                // WiFi/BLE Settings
                broadcast_speed: parseInt(document.getElementById('broadcast_speed').value),
                ap_ssid: "GhostNet",
                ap_password: "GhostNet",

                // RGB Settings
                rainbow_mode: document.getElementById('rainbow_mode').checked,
                rgb_speed: parseInt(document.getElementById('rgb_speed').value),

                // Evil Portal Settings
                portal_url: document.getElementById('portal_url').value,
                portal_ssid: document.getElementById('portal_ssid').value,
                portal_password: document.getElementById('portal_password').value,
                portal_ap_ssid: document.getElementById('portal_ap_ssid').value,
                portal_domain: document.getElementById('portal_domain').value,
                portal_offline_mode: document.getElementById('portal_offline_mode').checked,

                // Power Printer Settings
                printer_ip: document.getElementById('printer_ip').value,
                printer_text: document.getElementById('printer_text').value,
                printer_font_size: parseInt(document.getElementById('printer_font_size').value),
                printer_alignment: parseInt(document.getElementById('printer_alignment').value),

                // Flappy Ghost Settings
                flappy_ghost_name: document.getElementById('flappy_name_text').value,
                hex_accent_color: document.getElementById('accent_color_hex').textContent,
                timezone_str: document.getElementById('timezone_select').value,
                gps_rx_pin: parseInt(document.getElementById('gps_rx_pin').value),
                display_timeout: parseInt(document.getElementById('display_timeout').value),
            };  

            const validationErrors = validateSettings(settings);
            if (validationErrors.length > 0) {
                alert('Please correct the following errors:\n' + validationErrors.join('\n'));
                return;
            }

            const rgbRedPin = parseInt(document.getElementById('rgb_red_pin').value);
            const rgbGreenPin = parseInt(document.getElementById('rgb_green_pin').value);
            const rgbBluePin = parseInt(document.getElementById('rgb_blue_pin').value);

            // Add to settings POST
            settings.rgb_red_pin = rgbRedPin;
            settings.rgb_green_pin = rgbGreenPin;
            settings.rgb_blue_pin = rgbBluePin;

            // Add validation
            if (!isNaN(rgbRedPin)) validateGpioRange(rgbRedPin, 'Red pin');
            if (!isNaN(rgbGreenPin)) validateGpioRange(rgbGreenPin, 'Green pin'); 
            if (!isNaN(rgbBluePin)) validateGpioRange(rgbBluePin, 'Blue pin');

            fetch('/api/settings', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(settings)
            })
            .then(response => {
                if (response.ok) {
                    alert('Settings saved successfully!');
                } else {
                    alert('Error saving settings.');
                }
            })
            .catch(error => console.error('Error saving settings:', error));
        }

        // Function to send Evil Portal command to the ESP32
        function startevilportal() {
            const PortalURL = document.getElementById('portal_url').value;
            let PortalSSID = document.getElementById('portal_ssid').value;
            let PortalPassword = document.getElementById('portal_password').value;
            let PortalAPSSID = document.getElementById('portal_ap_ssid').value;
            let PortalDomain = document.getElementById('portal_domain').value;

            // Validate inputs
            const errors = [];
            if (PortalURL === '') errors.push('Please enter a Portal URL or File Path.');
            if (PortalSSID === '') errors.push('Please enter a Portal SSID.');
            if (PortalPassword === '') errors.push('Please enter a Portal Password.');
            if (PortalAPSSID === '') errors.push('Please enter a Portal AP SSID.');
            if (PortalDomain === '') errors.push('Please enter a Portal Domain.');

            if (errors.length > 0) {
                alert('Please correct the following errors:\n' + errors.join('\n'));
                return;
            }

            // Wrap parameters in double quotes if they contain spaces
            PortalSSID = wrapInQuotesIfNeeded(PortalSSID);
            PortalPassword = wrapInQuotesIfNeeded(PortalPassword);
            PortalAPSSID = wrapInQuotesIfNeeded(PortalAPSSID);
            PortalDomain = wrapInQuotesIfNeeded(PortalDomain);

            const command = `startportal`;

            fetch('/api/command', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ command: command })
            })
            .then(response => {
                if (response.ok) {
                    alert('Evil Portal Executed Successfully... You Are now Disconnected From GhostNet');
                } else {
                    alert('Error Sending Evil Portal Command...');
                }
            })
            .catch(error => console.error('Error Sending Evil Portal Command...', error));
        }

        // Function to validate settings before saving
        function validateSettings(settings) {
            const errors = [];

            // Broadcast Speed: 5 - 1000 ms
            if (!(settings.broadcast_speed >= 5 && settings.broadcast_speed <= 1000)) {
                errors.push('Broadcast Speed must be between 5 and 1000 ms.');
            }

            // RGB Speed: 15 - 50
            if (!(settings.rgb_speed >= 15 && settings.rgb_speed <= 50)) {
                errors.push('RGB Speed must be between 15 and 50.');
            }

            // Printer Font Size: 10 - 72
            if (!(settings.printer_font_size >= 10 && settings.printer_font_size <= 72)) {
                errors.push('Printer Font Size must be between 10 and 72.');
            }

            

            return errors;
        }

        function wrapInQuotesIfNeeded(str) {
            if (str.startsWith('"') && str.endsWith('"')) {
                return str;
            } else {
                return `"${str}"`;
            }
        }

        // Function to send text to the printer
        function sendtoprinter() {
            const printerip = document.getElementById('printer_ip').value.trim();
            const printertext = document.getElementById('printer_text').value.trim();
            const fontsize = parseInt(document.getElementById('printer_font_size').value);
            const alignment = getPrinterAlignment();

            const errors = [];

            if (printerip === '') errors.push('Please enter a Printer IP.');
            if (printertext === '') errors.push('Please enter text to send to the printer.');
            if (isNaN(fontsize) || fontsize < 10 || fontsize > 72) errors.push('Printer Font Size must be between 10 and 72.');

            if (errors.length > 0) {
                alert('Please correct the following errors:\n' + errors.join('\n'));
                return;
            }

            const finalprintertext = wrapInQuotesIfNeeded(printertext);
            const command = `powerprinter ${printerip} ${finalprintertext} ${fontsize} ${alignment}`;

            fetch('/api/command', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ command: command })
            })
            .then(response => {
                if (response.ok) {
                    alert('Printer connection command sent successfully!');
                    setTimeout(loadSettings, 3000);
                } else {
                    alert('Error sending Printer connection command.');
                }
            })
            .catch(error => console.error('Error sending Printer connection command:', error));
        }

        // Helper function to get printer alignment based on selected value
        function getPrinterAlignment() {
            const alignmentMap = {
                "0": "CM",
                "1": "TL",
                "2": "TR",
                "3": "BR",
                "4": "BL"
            };
            const value = document.getElementById('printer_alignment').value;
            return alignmentMap[value] || "CM";
        }

        // Function to connect to WiFi
        function connectToWiFi() {
            const ssid = document.getElementById('wifi_ssid').value.trim();
            const password = document.getElementById('wifi_password').value.trim();

            const errors = [];
            if (ssid === '') errors.push('Please enter a WiFi SSID.');
            if (password === '') errors.push('Please enter a WiFi password.');

            if (errors.length > 0) {
                alert('Please correct the following errors:\n' + errors.join('\n'));
                return;
            }

            const finalssid = wrapInQuotesIfNeeded(ssid);
            const finalpassword = wrapInQuotesIfNeeded(password);
            const command = `connect ${finalssid} ${finalpassword}`;

            fetch('/api/command', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ command: command })
            })
            .then(response => {
                if (response.ok) {
                    alert('WiFi connection command sent successfully!');
                    setTimeout(loadSettings, 3000);
                } else {
                    alert('Error sending WiFi connection command.');
                }
            })
            .catch(error => console.error('Error sending WiFi connection command:', error));
        }

        // Load settings on window load
        window.onload = function() {
            loadSettings();
        };

        function sendTerminalCommand() {
            const input = document.getElementById('terminalInput');
            const command = input.value.trim();
            
            if (command) {
                fetch('/api/command', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({command: command})
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    input.value = '';
                })
                .catch(error => console.error('Error:', error));
            }
        }

        function updateTerminal() {
            fetch('/api/logs')
                .then(response => response.text())
                .then(text => {
                    const termOutput = document.getElementById('terminalOutput');
                    const currentText = termOutput.innerText;
                    
                    // Only update if there's new text
                    if (text !== currentText) {
                        // Keep a buffer of the last 1000 lines
                        const lines = text.split('\n');
                        const maxLines = 1000;
                        
                        if (lines.length > maxLines) {
                            text = lines.slice(-maxLines).join('\n');
                        }
                        
                        termOutput.innerText = text;
                        
                        // Smooth scroll to bottom with a small delay
                        setTimeout(() => {
                            termOutput.scrollTop = termOutput.scrollHeight;
                        }, 50);
                    }
                })
                .catch(error => console.error('Error:', error));
            
            setTimeout(updateTerminal, 1000);
        }

        // Add event listener for Enter key in terminal input
        document.getElementById('terminalInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const input = this;
                const command = input.value.trim();
                
                if (command) {
                    // Disable input while command is processing
                    input.disabled = true;
                    
                    fetch('/api/command', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({command: command})
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        input.value = '';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        const termOutput = document.getElementById('terminalOutput');
                        termOutput.innerText += '\nError executing command: ' + error.message;
                    })
                    .finally(() => {
                        // Re-enable input and focus it
                        input.disabled = false;
                        input.focus();
                    });
                }
            }
        });

        // Start polling for terminal updates
        updateTerminal();
    </script>
</body>
</html>
